package com.boot.hospital.score.core.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.boot.hospital.score.common.enums.ResultCodeEnum;
import com.boot.hospital.score.common.util.JwtUtil;
import com.boot.hospital.score.common.wrapper.ResponseWrapper;
import com.boot.hospital.score.core.service.ExpertService;
import com.boot.hospital.score.dao.entity.Expert;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/expert")
@Slf4j
@PropertySources(value = {
        @PropertySource(value = {"classpath:important.properties", "classpath:application.properties"}, encoding = "utf-8")
})
@EnableAutoConfiguration
public class ExpertController {

    @Resource
    private ExpertService expertService;

    //    @ApiOperation("查询所有专家信息")
//    @GetMapping(value = "/selectAll")
//    public ResponseWrapper<Object> selectAll() {
//        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
//        List<Expert> expertList = expertService.selectAll();
//        responseWrapper.setData(expertList);
//        return responseWrapper;
//    }


    @ApiOperation("添加专家信息")
    @PostMapping(value = "/addExpert")
    public ResponseWrapper<Object> addExpert(@RequestParam Map<String, String> params) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {

            String password = params.get("password");

            Expert expert = new Expert();

            expert.setExpertName(params.get("expertName"));
            expert.setPassword(params.get("password"));
            expert.setAffiliate(params.get("affiliate"));
            expert.setDuty(params.get("duty"));
            expert.setReviewId(Integer.valueOf(params.get("reviewId")));
            expert.setMemo(params.get("memo"));

            if (expert.getExpertName().equals("")) {
                responseWrapper.setMsg("专家名称为空");
                responseWrapper.setCode(ResultCodeEnum.ADD_FAIL.getName());
                return responseWrapper;
            }
            if (expert.getReviewId() == null) {
                responseWrapper.setMsg("评审项目ID为空");
                responseWrapper.setCode(ResultCodeEnum.ADD_FAIL.getName());
                return responseWrapper;
            }
            if (expert.getPassword().equals("")) {
                responseWrapper.setMsg("密码为空");
                responseWrapper.setCode(ResultCodeEnum.ADD_FAIL.getName());
                return responseWrapper;
            }
            if (expertService.getExpertByExpertName(expert.getExpertName()) != null) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("用户名称已存在");
                return responseWrapper;
            }

            expert.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

            int result = expertService.insert(expert);
            if (result > 0) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
            } else {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.ADD_FAIL.getName());
            }
        } catch (Exception e) {
            responseWrapper.setMsg(ResultCodeEnum.FAIL.getName());
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }

        return responseWrapper;
    }

    @ApiOperation("批量删除专家信息")
    @DeleteMapping("/deleteExperts")
    public ResponseWrapper<Object> deleteExperts(@RequestBody List<String> expertIds) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {
            if (expertIds.size() <= 0) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("id为空");
                return responseWrapper;
            }
            int result = expertService.deleteExpertsByIds(expertIds);
            if (result > 0) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
            } else {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                responseWrapper.setMsg("删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除专家信息：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }

    @ApiOperation("修改专家信息")
    @PostMapping(value = "/updateExpert")
    public ResponseWrapper<Object> updateExpert(@RequestParam Map<String, String> params) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {

            Expert expert = new Expert();

            expert.setExpertName(params.get("expertName"));
            expert.setPassword(params.get("password"));
            expert.setAffiliate(params.get("affiliate"));
            expert.setDuty(params.get("duty"));
            expert.setReviewId(Integer.valueOf(params.get("reviewId")));
            expert.setMemo(params.get("memo"));
            expert.setExpertId(params.get("id"));

            int result = expertService.updateExpert(expert);
            if (result > 0) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
            } else {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.UPDATE_FAIL.getName());
            }
        } catch (Exception e) {
            log.error("修改专家信息：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }

    @ApiOperation("分页和模糊查询")
    @GetMapping(value = "/getExperts/{page}/{size}")
    public ResponseWrapper<Object> searchByPage(@PathVariable Integer page, @PathVariable Integer size, @RequestParam String search, @RequestParam Integer reviewId) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {
            Map<String, Object> params = new HashMap<>();
            if (search.equals("null") || search.equals("NULL")) {
                params.put("search", "");
            }
            params.put("pageSize", size);
            params.put("offset", page);
            params.put("search", search);
            params.put("reviewId", reviewId);

            List<Expert> expertList = expertService.selectByPageAndSearch(params);
            responseWrapper.setData(expertList);
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
            responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
        } catch (Exception e) {
            log.error("分页和模糊查询失败：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }

    @ApiOperation("检验秘钥")
    @GetMapping(value = "/testToken")
    public ResponseWrapper<Object> testToken(HttpServletRequest request) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {
            // 处理自己的逻辑业务
            // 此时我们想要获取 token中的用户信息，token经过拦截器拦截绝对是正确的
            String token = request.getHeader("token");

            DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);

            Expert expert = new Expert();
            expert.setExpertId(tokenInfo.getClaim("expertId").asString());
            expert.setExpertName(tokenInfo.getClaim("expertName").asString());
            expert.setAffiliate(tokenInfo.getClaim("affiliate").asString());
            expert.setDuty(tokenInfo.getClaim("duty").asString());
            expert.setReviewId(Integer.valueOf(tokenInfo.getClaim("reviewId").asString()));

            // 返回用户的相关信息的map集合
            responseWrapper.setData(expert);
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
            responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
        } catch (Exception e) {
            log.error("检验秘钥：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }

        return responseWrapper;
    }

    @ApiOperation("专家登录")
    @PostMapping("/expertLogin")
    public ResponseWrapper<Object> expertLogin(@RequestParam Map<String, String> params) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {

            Expert expert = new Expert();

            expert.setExpertName(params.get("username"));
            expert.setPassword(params.get("password"));

            Expert lawExpert = expertService.getExpertByExpertName(expert.getExpertName());

            if (lawExpert != null) {
                String password = lawExpert.getPassword();

                String loginPassword = params.get("password");
                loginPassword = DigestUtils.md5DigestAsHex(loginPassword.getBytes());

                if (password.equals(loginPassword)) {

                    //密码正确
                    Map<String, String> info = new HashMap<>();
                    info.put("expertName", lawExpert.getExpertName());
                    info.put("expertId", lawExpert.getExpertId());
                    info.put("affiliate", lawExpert.getAffiliate());
                    info.put("duty", lawExpert.getDuty());
                    info.put("reviewId", String.valueOf(lawExpert.getReviewId()));
                    String token = JwtUtil.createToken(info);

                    HashMap<String, Object> loginInfo = new HashMap<>();

                    loginInfo.put("token", token);

                    responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                    responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
                    responseWrapper.setData(loginInfo);
                } else {
                    log.error("账号密码错误");
                    responseWrapper.setMsg(ResultCodeEnum.PASSWORD_ERROR.getName());
                    responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                }
            } else {
                log.error("用户名不存在");
                responseWrapper.setMsg(ResultCodeEnum.LOGINNAME_NOT_EXIT_ERROR.getName());
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
            }
        } catch (Exception e) {
            log.error("用户登陆失败：{}", ExceptionUtils.getStackTrace(e));

            responseWrapper.setMsg(ResultCodeEnum.PASSWORD_ERROR.getName());
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }
}